<?php

declare(strict_types=1);

namespace DreamCat\ControllerParamGen\Decoder;

use DreamCat\ControllerParamGen\Exception\DecodeFailed;
use DreamCat\ControllerParamGen\HttpBodyDecodeInterface;
use JetBrains\PhpStorm\Pure;

/**
 * json消息体解码
 * @author vijay
 */
class JsonBodyDecoder implements HttpBodyDecodeInterface
{
    /**
     * @inheritDoc
     */
    #[Pure]
    public function match(string $contentType): bool
    {
        return str_contains($contentType, "application/json");
    }

    /**
     * @inheritDoc
     */
    public function parseBody(string $bodyText): mixed
    {
        $body = json_decode($bodyText, true);
        $lastError = json_last_error();
        if ($lastError) {
            throw new DecodeFailed(
                "json decode error: " . json_last_error_msg() . " body = {$bodyText}",
                $lastError
            );
        }
        return $body;
    }
}

# end of file
